<?php
/**
 * 张榜
 * 更新时间：每周三，0点
 */
ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\cache\wiki\WikiRanking as cacheWikiRanking;
use Biz\model\wiki\WikiRankingCateHotUp;
use Biz\model\wiki\WikiRankingConfig;
use Biz\model\wiki\WikiRankingCatePublic;
use Biz\model\wiki\WikiRankingWeek;
use Biz\service\wikiRanking\Ranking;


const HOT_UP_RANKING_ID = 10000;
const PUBLIC_RANKING_ID = 10001;

$start = time();
$dayArr = Ranking::getCreateRankingDay();
$day = $dayArr['day'];
$now = date('Ymd');
if ($day != $now) {
    var_dump('当前日期为：' . $now . '不能张第「' . $day . '」的榜单');
    return false;
}
$info = WikiRankingWeek::getByWhere(['ranking_day' => $day]);
if (!$info) {
    var_dump('不存在的榜单期数');
    return false;
}
$lastWeekDay = getLastWeekDay($day);
$brandRankingNameForMsg = [];
$rankingData = [];
getHotUpRanking($day , $lastWeekDay , $rankingData);
getCatePublic($day , $lastWeekDay , $rankingData);
showRanking($day,  $rankingData, $brandRankingNameForMsg);
//更新上榜周数
ShowContinueWeek($day);
sendMsg($day , $brandRankingNameForMsg);

/*放榜中
 *
 * */
function getHotUpRanking($day ,$lastWeekDay , &$rankingData){
    //热度榜张榜中
    $where = [
        'ranking_day' => $day,
        'ranking_state[!]' => WikiRankingCateHotUp::RANKING_STATE_DEL,
        'ORDER' => ['score' => 'DESC' , 'up_percent'=>'DESC']
    ];
    var_dump('热度榜张榜中……');
    $hotList = WikiRankingCateHotUp::selectByWhere($where);
    foreach ($hotList as $index => $row) {
        $topNum = $index + 1;
        if ($index < 30) {
            $rankingData['show_hot'][] = [
                'id' => $row['id'],
                'brand_id' => $row['brand_id'],
                'basic_id' => $row['basic_id'],
                'top_num' => $topNum,
            ];
        }else{
            $rankingData['hide_hot'][] = [
                'id' => $row['id'],
                'brand_id' => $row['brand_id'],
                'basic_id' => $row['basic_id'],
                'top_num' => $topNum,
            ];
        }
        $lastTopNum = $lastWeekDay ? WikiRankingCateHotUp::getByWhere(['ranking_day' => $lastWeekDay,  'basic_id' => $row['basic_id'], 'ranking_state[!]' => WikiRankingCateHotUp::RANKING_STATE_DEL], 'top_num') : 0;
        $lastTopNum = !empty($lastTopNum) ? $lastTopNum : 0;
        WikiRankingCateHotUp::updateData(['top_num' => $topNum, 'last_top_num' => $lastTopNum], ['id' => $row['id']]);
    }
}

/*口碑放榜中
 *
 * */
function getCatePublic($day ,$lastWeekDay , &$rankingData){
    //口碑榜张榜中
    $where = [
        'ranking_day' => $day,
        'ranking_state[!]' => WikiRankingCateHotUp::RANKING_STATE_DEL,
        'ORDER' => ['score' => 'DESC']
    ];
    var_dump('口碑榜张榜中……');
    $publicPraiseList = WikiRankingCatePublic::selectByWhere($where);
    foreach ($publicPraiseList as $index => $row) {
        $topNum = $index + 1;
        if ($index < 30) {
            $rankingData['show_public_praise'][] = [
                'id' => $row['id'],
                'brand_id' => $row['brand_id'],
                'basic_id' => $row['basic_id'],
                'top_num' => $topNum,
            ];
        }else{

            $rankingData['hide_public_praise'][] = [
                'id' => $row['id'],
                'brand_id' => $row['brand_id'],
                'basic_id' => $row['basic_id'],
                'top_num' => $topNum,
            ];

        }
        $lastTopNum = $lastWeekDay ? WikiRankingCatePublic::getByWhere(['ranking_day' => $lastWeekDay, 'basic_id' => $row['basic_id'], 'ranking_state[!]' => WikiRankingCatePublic::RANKING_STATE_DEL], 'top_num') : 0;
        $lastTopNum = !empty($lastTopNum) ? $lastTopNum : 0;
        WIkiRankingCatePublic::updateData(['top_num' => $topNum, 'last_top_num' => $lastTopNum], ['id' => $row['id']]);
    }
}

/*更新上榜次数
 *
 * */
function ShowContinueWeek( $day){
    var_dump('更新连续上榜次数');
    $rankingDay = $day;
    $weekDays = WikiRankingWeek::selectByWhere(['ranking_day[<]' => $rankingDay, 'ORDER' => ['ranking_day' => 'DESC']], 'ranking_day');
    var_dump($weekDays);
    //热度榜
    $where = ['ranking_day' => $rankingDay, 'ranking_state' => WIkiRankingCatePublic::RANKING_STATE_SHOW];
    $hotList = WikiRankingCateHotUp::selectByWhere($where);
    foreach ($hotList as $row) {
        $continueWeek = 1;
        foreach ($weekDays as $weekDay) {
            $info = WIkiRankingCatePublic::getByWhere(['ranking_day' => $weekDay, 'ranking_state' => WIkiRankingCatePublic::RANKING_STATE_SHOW, 'basic_id' => $row['basic_id']]);
            if (!empty($info)) {
                $continueWeek = $continueWeek + 1;
            } else {
                break;
            }
        }
        var_dump('截止到' . $rankingDay  . '#basic Id：' . $row['basic_id'] . '#连续上热度榜:' . $continueWeek . '次');
        WikiRankingCateHotUp::updateData(['continue_week' => $continueWeek], ['ranking_day' => $rankingDay, 'basic_id' => $row['basic_id']]);
    }
    //口碑榜
    $publicPraiseList = WIkiRankingCatePublic::selectByWhere($where);
    foreach ($publicPraiseList as $row) {
        $continueWeek = 1;
        foreach ($weekDays as $weekDay) {
            $info = WIkiRankingCatePublic::getByWhere(['ranking_day' => $weekDay, 'ranking_state' => WIkiRankingCatePublic::RANKING_STATE_SHOW, 'basic_id' => $row['basic_id']]);
            if (!empty($info)) {
                $continueWeek = $continueWeek + 1;
            } else {
                break;
            }
        }
        var_dump('截止到' . $rankingDay  . '#basic Id：' . $row['basic_id'] . '#连续上口碑榜:' . $continueWeek . '次');
        WIkiRankingCatePublic::updateData(['continue_week' => $continueWeek], [ 'ranking_day' => $rankingDay, 'basic_id' => $row['basic_id']]);
    }
}

/*正式放榜单
 *
 * */
function showRanking($day,  $rankingData, &$brandRankingNameForMsg)
{
    $showHotData = $rankingData['show_hot'];
    $showPublicPraiseData = $rankingData['show_public_praise'];
    $hideHotData = $rankingData['hide_hot'] ? : [];
    $hidePublicPraiseData = $rankingData['hide_public_praise'] ? : [];
    //分类榜单下，Tab 下不少于 5 条数据的才可展示；
    //二级分类下有不少于两个榜（如热度榜+口碑榜、热度榜+品牌榜），且当前热度榜有大于等于 5 个 Wiki 的榜单才计为有效榜单；
    //仅有效榜单才可在各曝光位被推荐或被搜索或在相关商品和品牌主页中作为标签展示。
    //热度榜
    //热度榜单缓存
    if ($showHotData && is_array($showHotData)) {
        foreach ($showHotData as  $row) {
            $topNum = $row['top_num'];
            cacheWikiRanking::addBasicWikiHotUpRanking($day, $row['basic_id'], $topNum, HOT_UP_RANKING_ID);
            if ($row['brand_id']) {
                $brandRankingName = '热度飙升榜';
                if (!isset($brandRankingNameForMsg[$row['brand_id']])) {
                    $brandRankingNameForMsg[$row['brand_id']][] = $brandRankingName;
                } else if (!in_array($brandRankingName, $brandRankingNameForMsg[$row['brand_id']])) {
                    $brandRankingNameForMsg[$row['brand_id']][] = $brandRankingName;
                }
            }
            $data = [
                'ranking_state' => WikiRankingCateHotUp::RANKING_STATE_SHOW,
            ];
            WikiRankingCateHotUp::updateData($data, ['id' => $row['id']]);
        }
    }

    if ($hideHotData) {
        foreach ($hideHotData as $row) {
            $data = [
                'ranking_state' => WikiRankingCateHotUp::RANKING_STATE_HIDE,
            ];
            WikiRankingCateHotUp::updateData($data, ['id' => $row['id']]);
        }
    }
    //口碑榜
    if ($showPublicPraiseData && is_array($showPublicPraiseData)) {
        foreach ($showPublicPraiseData as  $row) {
            $topNum = $row['top_num'];
            //口碑榜单缓存
            cacheWikiRanking::addBasicWikiCatePublicRanking($day, $row['basic_id'], $topNum, PUBLIC_RANKING_ID);
            if ($row['brand_id']) {
                $brandRankingName =  '住友口碑榜';
                if (!isset($brandRankingNameForMsg[$row['brand_id']])) {
                    $brandRankingNameForMsg[$row['brand_id']][] = $brandRankingName;
                } else if (!in_array($brandRankingName, $brandRankingNameForMsg[$row['brand_id']])) {
                    $brandRankingNameForMsg[$row['brand_id']][] = $brandRankingName;
                }
            }
            $data = [
                'ranking_state' => WIkiRankingCatePublic::RANKING_STATE_SHOW,
            ];
            WIkiRankingCatePublic::updateData($data, ['id' => $row['id']]);
        }
    }

    if ($hidePublicPraiseData) {
        foreach ($hidePublicPraiseData as $row) {
            $data = [
                'ranking_state' => WikiRankingCateHotUp::RANKING_STATE_HIDE,
            ];
            WIkiRankingCatePublic::updateData($data, ['id' => $row['id']]);
        }
    }
}


/*发送信息
 *
 * */
function sendMsg( $day,$brandRankingNameForMsg){
    foreach ($brandRankingNameForMsg as $brandId => $row) {
        $msg = '恭喜你被住友选入了新一期 %s 中，打开好好住 App 进入好物频道就可以看到上榜情况了，想要玩转榜单就快点击这里查看《榜单秘籍》吧';
        $msgTemp = implode('、', $row);
        $msg = sprintf($msg, $msgTemp);
        \Biz\service\BrandIndex::writeMsg($brandId, \Biz\model\brandIndex\BrandMsg::MSG_TYPE_PASS, \Biz\model\brandIndex\BrandMsg::MSG_SOURCE_RANKING, $msg);
    }
    var_dump(date('Y-m-d-H-i-s') . '第' . $day . '期榜单张榜完成');
}

function getLastWeekDay($day)
{
    $lastWeekInfo = WikiRankingWeek::getByWhere(['ORDER' => ['ranking_day' => 'DESC'], 'ranking_day[<]' => $day]);
    $lastWeekDay = $lastWeekInfo ? $lastWeekInfo['ranking_day'] : 0;
    return $lastWeekDay;
}